import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/str_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_decoration.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_shadow.dart';

import '../../config/kq_pad_global.dart';
import '../../resources/images.dart';
import '../../resources/kq_pad_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_pad_divider.dart';
import '../filter/kq_filter_check_view.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 单选组件
///
/// [ItemType.radio]
///
/// 结合 KqPadFormEntity 使用
///
/// @author 周卓
///
class KqPadRadioItemView extends StatefulWidget {
  /// 通用属性
  final KqPadFormEntity entity;

  /// 单选组件单选点击回调
  final Function(KqPadFormEntity entity, RadioData radioData)? onRadioChanged;

  const KqPadRadioItemView(
      {Key? key, required this.entity, this.onRadioChanged})
      : super(key: key);

  @override
  KqPadRadioItemViewState createState() => KqPadRadioItemViewState();
}

class KqPadRadioItemViewState extends State<KqPadRadioItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    calTitleWidth();
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  double titleWidth = 0;

  calTitleWidth() {
    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    String titleWidthString = "";
    for (int i = 0; i < (widget.entity.titleFixedWidthCharCount ?? 8); i++) {
      titleWidthString += "中";
    }
    titleWidth = measureTextWidth(titleWidthString, textStyle: titleStyle);
  }

  @override
  void didUpdateWidget(covariant KqPadRadioItemView oldWidget) {
    widget.entity.widgetState = this;
    calTitleWidth();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    var bgColor = widget.entity.backgroundColor;

    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    bool isHideInputBox =
        KqPadThemeManager.instance.getConfig().formConfig.isHideInputBox !=
                null &&
            KqPadThemeManager.instance.getConfig().formConfig.isHideInputBox!;

    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          Container(
            color: bgColor,
            padding: EdgeInsets.only(
                right: widget.entity.paddingHorizontal ??
                    KqPadThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingHorizontal ??
                    8.dm,
                top: widget.entity.paddingVertical ?? 0,
                bottom: widget.entity.paddingVertical ?? 0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                /// 是否必填
                Container(
                  alignment: Alignment.centerRight,
                  width: widget.entity.paddingHorizontal ??
                      KqPadThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      8.dm,
                  padding: EdgeInsets.only(
                    top: 7.dm,
                    right: 1.dm,
                  ),
                  child: Text(
                    "∗",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontSize: KqPadThemeManager.instance
                                .getConfig()
                                .formConfig
                                .mustInputFontSize ??
                            7.dm,
                        color: widget.entity.mustInput
                            ? KqPadThemeColors.textRed
                            : widget.entity.mustInputStarColor ??
                                KqPadThemeColors.bgTransparent),
                  ),
                ),

                // 标题
                Container(
                  width: titleWidth + (isHideInputBox ? 0 : 6.dm),
                  padding: EdgeInsets.only(
                      right: isHideInputBox ? 0 : 6.dm, top: 0.5.dm + 7.dm),
                  alignment: Alignment.centerRight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      /// 左边自定义控件
                      /// 自定义布局，来自实体类
                      widget.entity.customLeftView != null
                          ? widget.entity.customLeftView!(widget.entity)
                          : Container(),

                      if (widget.entity.title.isNotEmpty)
                        Expanded(
                          child: Text(
                            widget.entity.title.fixSoftWrap() ?? '',
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            textAlign: widget.entity.titleTextAlign,
                            style: titleStyle,
                          ),
                        ),
                    ],
                  ),
                ),

                /// 右侧按钮组
                Expanded(
                  child: Container(
                    constraints: widget.entity.isEditable()
                        ? BoxConstraints(minHeight: 20.dm)
                        : null,
                    padding: widget.entity.isEditable()
                        ? EdgeInsets.only(
                            top: 0.5.dm + 7.dm, left: 2.dm, right: 2.dm)
                        : EdgeInsets.symmetric(
                            vertical: widget.entity.paddingVertical ?? 7.dm),
                    margin: widget.entity.isEditable()
                        ? EdgeInsets.only(top: 2.dm, bottom: 2.dm)
                        : null,
                    decoration: widget.entity.isEditable() && !isHideInputBox
                        ? KqBoxDecoration(
                            boxShadow: [
                              KqBoxShadow(
                                  offset: Offset(0.5.dm, 0.5.dm),
                                  blurRadius: 0,
                                  spreadRadius: 0,
                                  color: const Color(0x80FFFFFF)),
                              KqBoxShadow(
                                  offset: Offset(0, 0.5.dm),
                                  blurRadius: 3.dm,
                                  spreadRadius: 0,
                                  inset: true,
                                  color: const Color(0xFFB2B7CE)),
                              KqBoxShadow(
                                  offset: Offset(0.5.dm, 0.5.dm),
                                  blurRadius: 0.5.dm,
                                  spreadRadius: 0,
                                  inset: true,
                                  color: const Color(0xFFC9CCD9)),
                            ],
                            borderRadius: BorderRadius.circular(1.dm),
                            color: KqPadThemeColors.bgWhite,
                          )
                        : null,
                    child: LayoutBuilder(
                      builder: (context, constraints) {
                        if (widget.entity.isEditable()) {
                          return Padding(
                            padding: EdgeInsets.only(
                                bottom: 7.dm, left: 6.dm, right: 6.dm),
                            child: Wrap(
                              alignment: WrapAlignment.start,
                              spacing: 10.dm,
                              runSpacing: 6.dm,
                              children: _renderEditableRadioButtonList(),
                            ),
                          );
                        }
                        double maxWidth = constraints.maxWidth;
                        return Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: _renderNonEditableWidget(maxWidth),
                        );
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),

          /// 分割线
          Visibility(
              visible: !widget.entity.isEditable(),
              child: const KqPadDivider()),

          /// 分隔栏
          Visibility(
              visible: widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
          Visibility(
              visible: widget.entity.showDivider2, child: const KqPadDivider()),
          Visibility(
              visible: widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
        ],
      ),
    );
  }

  /// 非编辑模式下
  List<Widget> _renderNonEditableWidget(double maxWidth) {
    //非编辑模式，只显示选中按钮的文字
    double maxItemWidth = maxWidth / widget.entity.radioData!.length;
    for (var data in widget.entity.radioData!) {
      if (data.itemId == widget.entity.valueForSubmit) {
        return [
          LimitedBox(
            maxWidth: maxItemWidth - 8.dm,
            child: Text(
              data.item,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  fontSize: widget.entity.contentFontSize ??
                      KqPadThemeManager.getFormConfig().contentFontSize ??
                      7.dm,
                  color: KqPadThemeColors.text59),
            ),
          )
        ];
      }
    }
    return [];
  }

  /// 编辑模式下
  List<Widget> _renderEditableRadioButtonList() {
    TextStyle textStyle = TextStyle(
        fontSize: widget.entity.contentFontSize ??
            KqPadThemeManager.getFormConfig().contentFontSize ??
            7.dm,
        color: widget.entity.contentColor ?? KqPadThemeColors.text26);
    return widget.entity.radioData
            ?.map(
              (e) => _renderRadioButtonItem(e, widget.entity.radioData!.length,
                  textStyle, widget.entity.radioData!.indexOf(e)),
            )
            .toList() ??
        [];
  }

  /// 画笔，用于测量
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);

  /// 获取文本宽度
  double measureTextWidth(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.width;
  }

  Widget _renderRadioButtonItem(
      RadioData data, int itemCount, TextStyle textStyle, int index) {
    Widget child = Text(
      data.item,
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      style: textStyle.copyWith(
          color: data.itemId == widget.entity.valueForSubmit
              ? Colors.white
              : KqPadThemeColors.text26),
    );
    return KqPadFilterCheckView(
      onTap: () {
        setState(() {
          if (widget.entity.canInvert == true) {
            if (widget.entity.valueForSubmit == data.itemId) {
              widget.entity.valueForSubmit = null;
              widget.entity.valueForShow = null;
            } else {
              widget.entity.valueForSubmit = data.itemId;
              widget.entity.valueForShow = data.item;
            }
          } else {
            widget.entity.valueForSubmit = data.itemId;
            widget.entity.valueForShow = data.item;
          }

          //回调
          widget.entity.onRadioChanged?.call(widget.entity, data);
          widget.onRadioChanged?.call(widget.entity, data);
        });
      },
      padding: EdgeInsets.symmetric(horizontal: 6.dm, vertical: 3.dm),
      text: data.item,
      selected: data.itemId == widget.entity.valueForSubmit,
      child: child,
    );
  }

  String? getPackageName(RadioData data, bool chosen) {
    return chosen
        ? (data.checkedImgPath != null ? null : KqPadGlobal.packageName)
        : (data.unCheckedImgPath != null ? null : KqPadGlobal.packageName);
  }

  /// 获取图片
  String getImgPath(RadioData data, bool chosen) {
    return chosen
        ? (data.checkedImgPath ?? Images.commonIcRadio16SelectedEnabled)
        : (data.unCheckedImgPath ?? Images.commonIcRadio16UnselectedEnabled);
  }
}

/// 单选数据
class RadioData {
  /// 显示名字
  String item;

  /// 选择后用户提交id
  String itemId;

  /// 选中的图片
  String? checkedImgPath;

  /// 未选中的图片
  String? unCheckedImgPath;

  /// 图片的包名，如果是组件库里的图片，要用[KqPadGlobal.packageName]
  String? package;

  RadioData({
    required this.item,
    required this.itemId,
    this.checkedImgPath,
    this.unCheckedImgPath,
    this.package,
  });
}
